package com.liugh.asyn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 有的异步执行任务获取结果也需要通过回调，因此在AsyncJob的基础上封装这个类
 */
public abstract class AsyncExecuteJob<R> extends AsyncJob<R> {

    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncExecuteJob.class);

    @Override
    public void run() {
        if (null == mAsyncJobListener || mAsyncJobListener.beforeExecute(this)) {
            asyncExecuteJob(new AsyncExecuteListener<R>() {
                @Override
                public void onSuccess(AsyncJobResult<R> result) {
                    if (null != mAsyncJobListener) {
                        mAsyncJobListener.afterExecute(AsyncExecuteJob.this, result);
                    }
                }

                @Override
                public void onFail(AsyncJobResult<R> result) {
                    mAsyncJobListener.afterExecute(AsyncExecuteJob.this, result);
                }
            });
        }

    }

    @Override
    protected AsyncJobResult<R> runJob() {
        return AsyncJobResult.INVALID_RESULT;
    }


    /**
     * 专门针对需要异步获取结果的job
     * @param listener 统一获取异步执行结果的监听
     */
    protected abstract void asyncExecuteJob(AsyncExecuteListener<R> listener);


    /**
     * 异步执行结果回调
     * @param <R>
     */
    public interface AsyncExecuteListener<R> {

        default void onSuccess(AsyncJobResult<R> result) {
            // do nothing
        }

        default void onFail(AsyncJobResult<R> result) {
            LOGGER.error("异步任务执行失败， error msg: {}", result.getResultException().getMessage());
        }
    }



}
